package com.allwees.bs.module.core.rest;

import com.allwees.bs.core.modelbase.branch.BranchUser;
import com.allwees.bs.core.modelbase.exception.AuthException;
import com.allwees.bs.core.modelbase.exception.AuthExceptionEnum;
import com.allwees.bs.core.modelbase.vo.R;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * REST Api Base
 *
 * @author yangylsky
 * @since 2019-09-30
 *
 */
public abstract class BaseApi {

    @GetMapping("/monitor/heartbeat")
    public R heartbeat() {
        return R.ok("The api is alive! - " + getClass().getSimpleName());
    }

	/**
	 * 获得当前登录用户
	 * @return
	 */
	public static BranchUser getCurrentUser() {
		return getCurrentUser(true);
	}

	public static BranchUser getCurrentUser(boolean shouldBeAuthenticated) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication == null || !(authentication.getPrincipal() instanceof BranchUser)) {
			if (shouldBeAuthenticated) {
				throw new AuthException(AuthExceptionEnum.NOT_LOGIN);
			}
			return null;
		}

		BranchUser user = (BranchUser)authentication.getPrincipal();
		if(!user.isEnabled()) {
			throw new AuthException(AuthExceptionEnum.ACCOUNT_DISABLED);
		}
		return user;
	}
}
